package com.project.dao.impl;

import com.project.bean.CutPageBean;
import com.project.bean.UserBean;
import com.project.dao.IUserDao;

import java.sql.SQLException;
import java.time.LocalDate;
import java.util.List;

public class UserDaoImpl extends BaseDao implements IUserDao {
    @Override
    public void add(UserBean userBean) {
        this.addObj(userBean);
    }

    @Override
    public void delById(int id) {
        this.updateDB("delete from t_user2 where pk_userId=?",id);
    }

    @Override
    public void updatePhoneById(int id, String phone) {
        this.updateDB("update t_user2 SET u_phone=? where pk_userId=?",phone,id);
    }

    @Override
    public List<UserBean> findAll() {
      return findDB("select * from t_user2",UserBean.class);
    }

    @Override
    public UserBean findById(int id) {
        return (UserBean) findDB("select * from t_user2 where pk_userId=?",UserBean.class,id).get(0);
    }

    @Override
    public CutPageBean<UserBean> catAll(int pageNo) {
        CutPageBean<UserBean> cutBean = new CutPageBean<>();
        this.setConnection();
        try {
            ps = con.prepareStatement("select * from t_user2 limit ?,?");
            ps.setObject(1,(pageNo-1)*CutPageBean.PAGENUM);
            ps.setObject(2,CutPageBean.PAGENUM);

            rs = ps.executeQuery();
            while (rs.next()){
                UserBean user = new UserBean();
                user.setId(rs.getInt("pk_userId"));
                user.setUserName(rs.getString("u_userName"));
                user.setPwd(rs.getString("u_pwd"));
                user.setBirthday(LocalDate.parse(rs.getString("u_birthday")));
                user.setPhone(rs.getString("u_phone"));

                cutBean.getList().add(user);
            }

            //获取总记录条数
            ps = con.prepareStatement("select count(*) c from t_user2");
            rs = ps.executeQuery();
            if (rs.next()){
                cutBean.setCount(rs.getInt("c"));
            }

        } catch (Exception throwables) {
            throwables.printStackTrace();
        }
        finally {
            this.closeConnection();
        }

        return cutBean;
    }

    public static void main(String[] args) {
        IUserDao dao = new UserDaoImpl();
//        dao.updatePhoneById(2,"14374382832");
//        System.out.println(dao.findAll());
        System.out.println(dao.catAll(2));
    }
}
